gpt4 book ai didi

asp.net - HttpWebRequest 抛出 404 异常

转载 作者:行者123 更新时间:2023-12-02 21:35:50 24 4
gpt4 key购买 nike

我发现 HttpWebRequest 对不存在的资源抛出 WebException。在我看来,这很奇怪,因为 HttpWebResponse 有 StatusCode 属性(NotFount 项存在)。您认为这有什么原因吗?或者这只是开发人员的问题?

var req = (HttpWebRequest)WebRequest.Create(someUrl);
using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) {
if (response.StatusCode == HttpStatusCode.OK) { ...}
}

最佳答案

这确实是一个令人沮丧的问题,可以通过使用以下扩展方法类并调用 request.BetterGetResponse() 来解决

//-----------------------------------------------------------------------
//
// Copyright (c) 2011 Garrett Serack. All rights reserved.
//
//
// The software is licensed under the Apache 2.0 License (the "License")
// You may not use the software except in compliance with the License.
//
//-----------------------------------------------------------------------

namespace CoApp.Toolkit.Extensions {
using System;
using System.Net;

public static class WebRequestExtensions {
public static WebResponse BetterEndGetResponse(this WebRequest request, IAsyncResult asyncResult) {
try {
return request.EndGetResponse(asyncResult);
}
catch (WebException wex) {
if( wex.Response != null ) {
return wex.Response;
}
throw;
}
}

public static WebResponse BetterGetResponse(this WebRequest request) {
try {
return request.GetResponse();
}
catch (WebException wex) {
if( wex.Response != null ) {
return wex.Response;
}
throw;
}
}
}
}

您可以在我关于此主题的博客文章 http://fearthecowboy.com/2011/09/02/fixing-webrequests-desire-to-throw-exceptions-instead-of-returning-status/ 中了解更多相关信息。

关于asp.net - HttpWebRequest 抛出 404 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3771065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com