0

I have created WCF Rest service that take input/para from client and save it in database and knowledge with identity of table in which data is added.When I am consuming service throgh client that is nothing but web application making url as web request and getting proper output.But when I am consuming through browser getting error. First I tried like this :-

http://localhost:Portnumber/Test.svc/ADD/Bodywash/Orange/50

after that like this ht

tp://localhost:Portnumber/Test.svc/ADD?Name=Bodywash&CategoryName=Orange&Price=50

I am getting error'Entpoint not found'.How to consume rest service through browser?Will I able to do that

// Code of service

-- Table
CREATE TABLE [dbo].[Product](
    [ProductId] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NULL,
    [CategoryName] [varchar](50) NULL,
    [Price] [int] NULL
) 

-- Sp
ALTER  procedure [dbo].[proc_InsertProduct]
(
@id int out,
@Name nvarchar(50),
@CategoryName nvarchar(50),
@Price int
)
as insert into Product
(
Name,
CategoryName,
Price
)
values
(
@Name,
@CategoryName,
@Price
)

set @id = @@identity
return @id


-- Interface

 public interface ITest
    {
        [WebInvoke(UriTemplate = "ADD/{Name}/{CategoryName}/{Price}", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        int InsertProduct(string Name, string CategoryName, string Price);
    }


-- class

 public class Test : ITest
 {
  public int InsertProduct(string Name, string CategoryName, string Price)
        {
            string constr = ConfigurationManager.ConnectionStrings["SampleConnectionString"].ConnectionString;
            SqlConnection con = new SqlConnection(constr);
            SqlCommand cmd = new SqlCommand("proc_InsertProduct", con);
            cmd.CommandType = CommandType.StoredProcedure;
            con.Open();
            cmd.Parameters.AddWithValue("@Name", Name);
            cmd.Parameters.AddWithValue("@CategoryName", CategoryName);
            cmd.Parameters.AddWithValue("@Price", Price);
            cmd.Parameters.Add("@id", SqlDbType.Int);
            cmd.Parameters["@id"].Direction = ParameterDirection.Output;//Output parameter 
            cmd.ExecuteNonQuery();
            con.Close();
           int result = (int)(cmd.Parameters["@id"].Value);
            return result;//returning id 
        }
    }



    // WebConfig
<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>

  <connectionStrings>
    <add name="SampleConnectionString" connectionString="Data Source=xxx.xxx.x.x;Initial Catalog=sample;Persist Security Info=True;User ID=sa;Password=xxxx" providerName="System.Data.SqlClient"/>
  </connectionStrings>

  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>


  <system.serviceModel>

    <services>
      <service name="RestApiTest.Test" behaviorConfiguration="serviceBehavior">
        <endpoint address="" binding="webHttpBinding" contract="RestApiTest.ITest" behaviorConfiguration="web">
        </endpoint>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
          <behavior name="serviceBehavior">
            <serviceMetadata httpGetEnabled="true"/>
            <serviceDebug includeExceptionDetailInFaults="false"/>
          </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>


    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>
Jui Test
  • 2,399
  • 14
  • 49
  • 76
  • _Will I able to do that_ - Yes, you can access GET endpoints of RESTful WCF via browser. But to identify your issue, you might need to provide the WCF code as well. The method you are trying to hit seems to be a POST method - if that method (ADD) is a POST method, then you cant hit it through browser. User Fiddler/Postman instead – Developer Nov 15 '16 at 06:46
  • Yes my request is post.I am inserting record into table.I will modify my question. – Jui Test Nov 15 '16 at 06:49
  • 1
    As I said earlier, if the method is POST, use Fiddler/Postman instead of hitting it from browser – Developer Nov 15 '16 at 07:36
  • Thanks @developer for ur help.I kept all code same just change method name from post to get.I know get for selecting and post for insert/update.Here I am insering data came from url into my table and returning my table id.Working fine in all browser.Will this consider as valid?or I will face any problem further.Because client might be accessing it through browser. – Jui Test Nov 15 '16 at 09:30

1 Answers1

0

Continuation from comments - updating as answer due to size limit of comments

This would work though I wont recommend doing it - respecting the HTTP Verbs, all get request should be GET, add should be POST, update should be PUT (PATCH in case for patches) and delete should be DELETE methods. I would suggest you to revert this method back to POST.

Because client might be accessing it through browser - By this, I'm assuming that you mean to say that this service will be consumed from client side using JavaScript code. If that is true, then you dont have to worry about it. if someone POSTs data (for eg, using $.ajax or $.post in case of jQuery) to your REST service, you will get data properly.

To make this method a standard POST method, please change the method signature to accept a comples object instead of getting Name, CategoryName & Price from the route. Change this int InsertProduct(string Name, string CategoryName, string Price); to something like int InsertProduct(Product product); where 'Product' class has required properties. You can find a sample implementation here - POST complex object to WCF REST.

Community
  • 1
  • 1
Developer
  • 6,240
  • 3
  • 18
  • 24