I have created Api controller and trying to add 1 api method but getting error when adding Route attribute on my api method:
This is my method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
public class MyController : ApiController
{
[AllowAnonymous]
[HttpPost]
[Route("api/abc/Get")] //Getting error :type or namespace Route could not be found
public async Task<object> Get()
{
}
}
My dll references:
But on Route Attribute i am getting error:
Error:Type or namespace Route could not be found
Probably you need to check if you have System.Web.Http assembly in your project references. if you used nuget please check if you have web api packages installed
you can check it here:
Related
I'm currently playing around with SourceGenerators and want to create a controller for each model of an existing DBContext.
I kickstarted the project with Scaffold-DbContext DemoDatabase and added the Person controller and the API is working fine. The project is in net6.0 and the generator is in netstandard2.0.
My handwritten Controller in the API Project looks exactly the same as the generated Code.
I managed to create the following file via the SourceGenerator
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Deltas;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.AspNetCore.OData.Routing.Controllers;
using DemoApi.Models;
namespace DemoApi.Controllers.v3
{
public partial class PersonController : ODataController
{
private ModelContext _context;
public PersonController(ModelContext context)
{
_context = context;
}
[HttpGet]
[EnableQuery]
public IActionResult Get()
{
return Ok(_context.Person.ToList());
}
}
}
However VisualStudio outputs an Error stating that the ModelContext does not contain a definition for Person. Either the syntax highlighting is not working properly or the I'm missing something because I can't navigate the generated files (eg. pressing F12 on ODataController just outputs: Cannot navigate to the symbol under the caret.)
Are there any possible way for the generated files to recognize the existing ModelContext because referncing is via using DemoApi.Models did not work or am I missing something?
Any help would be greatly appreciated
Thanks in advance
I'm familiar with PHP and JS, as well as MVC methodology, but I'm completely new to C# and have spent time looking for the documentation on this specific error.
I used dotnet new mvc to create a working app on port 5000. Also note, I am working in the Controller, not the model or view:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ExelonPrime.Models;
namespace OptimusPrime.Controllers{
public class ApiController : Controller
{
public void Help_Pdf()
{
Response.Write("test");
}
}
}
And the error I get (when trying to compile) is:
error CS1061: 'HttpResponse' does not contain a definition for 'Write' and no accessible extension method 'Write' accepting a first argument of type 'HttpResponse' could be found (are you missing a using directive or an assembly reference?)
If I'm missing a using directive, which one is it? I tried System.Web and that didn't work. How do I make this work?
I would recommend following through microsofts tutorial on using asp.net core.
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/?view=aspnetcore-2.2
As far as this specific instance, rather than using Response.Write, I would do this
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SampleWeb.Models;
namespace SampleWeb.Controllers
{
public class ApiController : Controller
{
[HttpGet]
public ActionResult<string> Help_Pdf()
{
return "test";
}
}
}
This specific sample might be helpful.
With this class, the url https://localhost:5001/api/Help_Pdf returns "test"
In ASPNET Core, when writing an API, it's more common to return an object, or POCO in stead of directly writing to the response stream (although it indeed is possible)
try changing your
public void Help_Pdf()
{
Response.Write("test");
}
to
[HttpGet()]
public IActionResult Help_Pdf()
{
return Ok();
}
this will return an 204 (no content), you can pass data however, to the OK function, to add a body to the response object.
If your trying to write directly to the response stream like that, you can do this:
public async Task Help_Pdf()
{
await Response.WriteAsync("Test");
}
However, I'd recommend not doing this in your actual app, the method should return an IActionResult. IMO it's not good practice to write directly to the stream in your controller methods (not very test friendly).
I am building a web service using web API controller. However, when I try to decorate any of my actions with [allowanonymous] attribute it doesn't work... here is an image
I just would like to know what is goning wrong in here...
Just fully qualify the name
[System.Web.Mvc.AllowAnonymous]
public ActionResult SomeAction()
{ ...
On the top of the page, use namespace like:
using System.Web.Mvc;
Just had to remove this using:
using System.Web.Http;
Because that namespace is for WebAPI, whereas System.Web.Mvc is for MVC Controllers. Using both namespaces in the same file may cause confusions for Authorize and AllowAnonymous, for example.
I am trying to implement OData routing in my ASP.NET web api. For guidance, I looked at this tutorial: http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/create-an-odata-v4-endpoint.
However, I keep on getting an error message in the MapODataServiceRoute() function. Apparently, the function is expecting a Microsoft.OData.Edm.IEdmModel, and my builder's GetEdmModel() function only returns Microsoft.Data.Edm.IEdmModel.
I did some research online. Microsoft.Data.Edm is a library for the older version of OData. Microsoft.OData.Edm is for OData v4.0, which is why I commented out Microsoft.Data.Edm in WebApiConfig.cs file. Here is my code.
using MyApp.Models;
// using Microsoft.Data.Edm;
using Microsoft.OData.Edm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.OData.Builder;
using System.Web.OData.Extensions;
using System.Web.OData.Routing;
namespace MyAppAPI
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Enable attribute routing
config.MapHttpAttributeRoutes();
// Enable OData routing
config.MapODataServiceRoute(
routeName: "MyApp",
routePrefix: "odata",
model: GetEdmModel());
// Conventional routing
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
// To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
// For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
config.EnableQuerySupport();
// To disable tracing in your application, please comment out or remove the following line of code
// For more information, refer to: http://www.asp.net/web-api
config.EnableSystemDiagnosticsTracing();
// Trying to get most browsers (i.e. Google Chrome) to return JSON
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
// Configure modesl to use Odata
public static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<ModelA>("ModelA");
builder.EntitySet<ModelB>("ModelB");
return builder.GetEdmModel();
}
}
}
However, I am still getting an error message:
Error 1 Cannot implicitly convert type 'Microsoft.Data.Edm.IEdmModel' to 'Microsoft.OData.Edm.IEdmModel'. An explicit conversion exists (are you missing a cast?)
Is there a clean way to get a Microsoft.OData.Edm.IEdmModel? Or am I going to have to just do a cast?
Replacing System.Web.Http.OData.Builder with System.Web.OData.Builder seems to work.
Here is the link with the explanation: https://devblogs.microsoft.com/aspnet/getting-started-with-asp-net-web-api-2-2-for-odata-v4-0/
I think this line pretty much sums it up though:
The assembly name and the root namespace are now System.Web.OData
instead of System.Web.Http.OData.
The headers I am using are now:
using MyApp.Models;
// using Microsoft.Data.Edm;
using Microsoft.OData.Edm;
using System.Net.Http.Headers;
using System.Web.Http;
// using System.Web.Http.OData.Builder;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
Please use
using Microsoft.AspNet.OData.Builder;
using Microsoft.AspNet.OData.Extensions;
instead of
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
i wish this will help,
i got same error when i tried to do same example, i just did the following by package manager console
1- unInstall-Package Microsoft.OData.Edm -Force
2- Install-Package Microsoft.OData.Edm
then it works fine with me.
I'm using MVC2 and VS2010 developing a website and need to use Application State global values. I can set a value like 'Application["hits"]=0;' in Global.asax but when trying to use the same in an MVC controller always get the following error:
The name 'Application' does not exist in the current context
I have also tried using in the Global.asax in order to define a global variable but it triggers the following error:
A namespace cannot directly contain members such as fields or methods
I'm looking for a way to define global Application State values that are available within all controllers of my MVC2 web application. Am I omitting something? My controller looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCApplication.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
Application["hits"] += 1;
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
}
}
I appreciate any solutions and/or suggestions.
Thanks
Mehrdad
I think that in MVC3 you can get access to an actual HttpApplicationState object via the
HttpContext.ApplicationInstance
property. That is:
HttpApplicationState application = HttpContext.ApplicationInstance.Application
In ASP.NET MVC2, i use
HttpContext.Application["foo"] = "bar";
and to get
HttpContext.Application["foo"]
You could use a static class with an internal dictionary and an indexer.
Also, have you tried HttpContext.Current.Application?