为什么在使用WebClient调用另一个控制器时返回500错误?

ogu*_*h4n 0 webclient asp.net-mvc-4 dotnet-httpclient

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

当我访问"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);
    }
Run Code Online (Sandbox Code Playgroud)

由以下异常创建的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
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 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
    }
}
Run Code Online (Sandbox Code Playgroud)

如果事实证明问题与目标控制器操作所依赖的ASP.NET会话有关,那么您可以使用该请求委派客户端cookie:

WebClient client = new WebClient();
client.Headers[HttpRequestHeader.Cookie] = Request.Headers["Cookie"];
Run Code Online (Sandbox Code Playgroud)