【问题标题】:WEB API response message not shown if no data found?如果未找到数据,则不显示 WEB API 响应消息?
【发布时间】:2020-11-30 09:18:28
【问题描述】:

我尝试使用 api,但未找到数据时未显示消息。

这是控制器代码:

public HttpResponseMessage GetPatResult(int Patid,int branchid)
{
    using (DBEntities1 entities = new DBEntities1())
    {
        var entity = entities.LAB_RESULTS_CLINIC_VIEW.Where(e => e.Patient_No == Patid && e.branchid==branchid).ToList();
        if (entity == null)
        {
            var message = string.Format("No Results Found ");
            HttpError err = new HttpError(message);
            return Request.CreateResponse(HttpStatusCode.NotFound, err);
           
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.OK, entity);
           
        }
    }
}

找到数据时,它会显示数据,但当 entity == null 时,它不显示消息并且只显示这一行:

此 XML 文件似乎没有任何关联的样式信息。文档树如下所示。

如果未找到数据,如何显示“未找到数据”消息?

我还更新了建议答案链接中的代码:

asp.net mvc api returning 'This XML file does not appear to have any style information associated with it. The document tree is shown below.'

这是 WebApiConfig 文件:

public static void Register(HttpConfiguration config)
        {
                 // Web API routes
            config.MapHttpAttributeRoutes();
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));
            var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
            config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
      
        }

这是 Global.asax.cs

public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        }
    }

更新代码后,现在在找不到数据时显示 []?

更新:

当 entityuser == false 时,我有另一个控制器 GetUsers,它显示消息“用户名或密码不正确”GetUsers 中 2 个控制器变量 entityuser 之间的差异 将 GetPatResult 中的作为布尔值和变量实体处理为字符串可能会影响布尔 VS 字符串?

这是控制器GetUsers的代码:

public HttpResponseMessage GetUsers(string username, string password, int branchid)
        {
            using (DBEntities1 entities = new DBEntities1())
            {
                var entityuser = entities.Users_web.Any(user => user.user_name.Equals(username, StringComparison.OrdinalIgnoreCase) && user.user_password == password && user.branch_id == branchid);

                if (entityuser == true)
                {
                    return Request.CreateResponse(HttpStatusCode.OK, entityuser);
                }
                else
                {
                   
                    var message = string.Format("User Name or password not Correct ");
                    HttpError err = new HttpError(message);
                    return Request.CreateResponse(HttpStatusCode.NotFound, err);
                }
            }

        }

更新 2:

我将控制器 GetPatResult 中的代码更改为 GetUsers 中的相同代码:

var entity = entities.LAB_RESULTS_CLINIC_VIEW.Where(e => e.Patient_No == Patid && e.branchid==branchid).ToList();
                if (entity == null) {} 

到这个代码

var entity = entities.LAB_RESULTS_CLINIC_VIEW.Any(e => e.Patient_No == Patid && e.branchid==branchid);
                if (entity == true) {}

在这种情况下,当没有找到数据时显示消息,但是当找到数据时,它不显示数据并且只显示真。

如何解决此问题并在未找到数据时显示消息并在找到数据时显示数据?

【问题讨论】:

标签: c# asp.net-mvc asp.net-web-api


【解决方案1】:

您的“实体”变量实际上并不是实体,而是一个 List。没有找到实体时,不是null而是空列表,可以用(!entity.Any())

查看
    var entity = entities.LAB_RESULTS_CLINIC_VIEW
        .Where(e => e.Patient_No == Patid && e.branchid==branchid)
        .ToList();
    if (!entity.Any())
    {
        var message = string.Format("No Results Found ");
        HttpError err = new HttpError(message);
        return Request.CreateResponse(HttpStatusCode.NotFound, err);
       
    }

如果您要获取单个实体或 null,则不要调用 .ToList() 而是调用 .FirstOrDefault()

    var entity = entities.LAB_RESULTS_CLINIC_VIEW
        .Where(e => e.Patient_No == Patid && e.branchid==branchid)
        .FirstOrDefault();
    if (entity == null)
    {
        var message = string.Format("No Results Found ");
        HttpError err = new HttpError(message);
        return Request.CreateResponse(HttpStatusCode.NotFound, err);
       
    }

【讨论】:

  • 非常感谢,这就是它的工作 List 而不是 null :)
【解决方案2】:

尝试改变

var message = string.Format("No Results Found ");
            HttpError err = new HttpError(message);
            return Request.CreateResponse(HttpStatusCode.NotFound, err);

到这里

    return Request.CreateResponse(HttpStatusCode.NotFound, "No Results Found");

或更好地使用现代 IHttpActionResult:

public IHttpActionResult GetPatResult(int Patid,int branchid)
{
    using (DBEntities1 entities = new DBEntities1())
    {
        var entity = entities.LAB_RESULTS_CLINIC_VIEW.Where(e => e.Patient_No == Patid && e.branchid==branchid).ToList();
        if (entity == null)
        {
            return NotFound("No Results Found ");
              
        }
        else
        {
            return Ok( entity);
           }
    }
}

【讨论】:

  • 同样的事情没有响应消息不起作用。
猜你喜欢
  • 2012-05-31
  • 1970-01-01
  • 2020-09-06
  • 2014-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-25
  • 2013-09-24
相关资源
最近更新 更多