0

我正在测试此链接上的示例:http: //msdn.microsoft.com/en-us/vs11trainingcourse_aspnetmvc4_topic5#_Toc319061802但使用 WebClient 调用另一个控制器时出现 500 错误。

当我直接访问“http://localhost:2323/photo/gallery 正在运行,但我尝试使用 WebClient 从操作中返回 500 错误?为什么?”

   public ActionResult Index()
    {
        WebClient client = new WebClient();
        var response = client.DownloadString(Url.Action("gallery", "photo", null, Request.Url.Scheme));


        var jss = new JavaScriptSerializer();
        var result = jss.Deserialize<List<Photo>>(response);

        return View(result);
    }

由以下异常创建的 500 错误:

[ArgumentNullException: Value cannot be null.
Parameter name: input]
   System.Text.RegularExpressions.Regex.Match(String input) +6411438
   Microsoft.VisualStudio.Web.Runtime.Tracing.UserAgentUtilities.GetEurekaVersion(String userAgent) +79
   Microsoft.VisualStudio.Web.Runtime.Tracing.UserAgentUtilities.IsRequestFromEureka(String userAgent) +36
   Microsoft.VisualStudio.Web.Runtime.Tracing.SelectionMappingExecutionListenerModule.OnBeginRequest(Object sender, EventArgs e) +181
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +69
4

2 回答 2

5

很难说。也许您正在调用的控制器操作需要授权?还是使用会话?当您发送 WebClient 请求时,它不会将客户端发送的任何客户端 cookie 委托给 Index 操作。

以下是调试代码并查看服务器返回的确切响应的方法:

WebClient client = new WebClient();
try
{
    var response = client.DownloadString(Url.Action("gallery", "photo", null, Request.Url.Scheme));
}
catch (WebException ex)
{
    using (var reader = new StreamReader(ex.Response.GetResponseStream()))
    {
        string responseText = reader.ReadToEnd(); // <-- Look here to get more details about the error
    }
}

如果事实证明问题与您的目标控制器操作所依赖的 ASP.NET 会话有关,那么您可以通过以下方式将请求委托给客户端 cookie:

WebClient client = new WebClient();
client.Headers[HttpRequestHeader.Cookie] = Request.Headers["Cookie"];
于 2012-05-24T09:07:02.410 回答
0

由于 User-Agent 标头而发生错误

分辨率为:

public ActionResult Index()
    {
        WebClient client = new WebClient();
        client.Headers[HttpRequestHeader.UserAgent] = Request.Headers["User-Agent"];
        var response = client.DownloadString(Url.Action("gallery", "photo", null, Request.Url.Scheme));


        var jss = new JavaScriptSerializer();
        var result = jss.Deserialize<List<Photo>>(response);

        return View(result);
    }
于 2012-05-24T11:01:58.497 回答