Asp.Net MVC框架:ContentResult类型与字符串 [英] Asp.Net Mvc: ContentResult vs. string
问题描述
我最近有人问为什么要使用,而不是返回字符串ContentResult类型。不幸的是我不能给比一个更好的答案:这是最好的做法
有没有人有一个更好的答案?
更新:为了更好地理解这个问题。有什么区别?
公众的ActionResult美孚(){
返回的内容(一些字符串);
}公共字符串栏(){
返回一些字符串;
}
如果您返回比其他东西的ActionResult
的默认行为是创建一个 ContentResult类型
包装呼唤的ToString()
的结果在任何你真的回来了(或 EmptyResult
如果您返回空
我能想到的原因,明确返回 ContentResult类型
:
- 这强化了这一事实,该方法是行动,而不是一个常规的方法,让开发者不太可能犯错误喜欢随便给它改名。
- 如果将来你需要指定内容类型,你将不需要改变方法签名。
- 它并不隐藏
的ToString()
电话。如果你返回字符串
,但返回复杂类型可以有意想不到的效果,这并不重要。
I recently was asked why to use ContentResult instead of returning string. Unfortunatly I could not give a better answer than: "It is best practice."
Does anyone have a better answer?
Update: To better understand the question. What's the difference?
public ActionResult Foo(){
return Content("Some string");
}
public string Bar(){
return "Some string";
}
If you return something other than an ActionResult
the default behavior is to create a ContentResult
wrapping the result of calling ToString()
on whatever you did return (or EmptyResult
if you returned null
. Reasons I can think of to explicitly return ContentResult
:
- It reinforces the fact that the method is an action, rather than a regular method, so devs are less likely to make mistakes like casually renaming it.
- If in the future you need to specify the content-type you won't need to change the method signature.
- It doesn't hide the
ToString()
call. This doesn't matter if you're returningstring
, but returning a complex type could have unexpected results.
这篇关于Asp.Net MVC框架:ContentResult类型与字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!