我正在测试此链接上的示例: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& completedSynchronously) +69
答案 0 :(得分: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"];
答案 1 :(得分:0)
错误
决议是:
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);
}